package com.probox.modules.controller.customer;

import com.probox.common.core.enums.DataStatus;
import com.probox.common.core.utils.SecurityUtils;
import com.probox.common.core.utils.StringUtils;
import com.probox.common.core.utils.poi.ExcelUtil;
import com.probox.common.core.web.controller.BaseController;
import com.probox.common.core.web.domain.AjaxResult;
import com.probox.common.core.web.page.TableDataInfo;
import com.probox.common.entity.service.customer.ICustomerInfoService;
import com.probox.common.log.annotation.Log;
import com.probox.common.log.enums.BusinessType;
import com.probox.common.security.annotation.PreAuthorize;
import com.probox.common.entity.domain.customer.CustomerFund;
import com.probox.common.entity.domain.customer.CustomerFundDetail;
import com.probox.common.entity.domain.customer.CustomerInfo;
import com.probox.common.entity.service.customer.ICustomerFundDetailService;
import com.probox.common.entity.service.customer.ICustomerFundService;

import com.probox.customer.api.domain.CustomerFundVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;


/**
 * 客户收益Controller
 *
 * @author zsy
 * @date 2021-06-18
 */
@RestController
@RequestMapping("/customer/fund")
public class CustomerFundController extends BaseController {
    @Autowired
    private ICustomerFundService customerFundService;

    @Autowired
    private ICustomerFundDetailService customerFundDetailService;

    @Autowired
    private ICustomerInfoService customerInfoService;

    /**
     * 查询客户收益列表
     */
    @PreAuthorize(hasPermi = "CustomerFund:fund:list")
    @GetMapping("/oldList")
    public TableDataInfo oldList(com.probox.common.entity.vo.customer.CustomerFundVo customerFundvo) {
        List<com.probox.common.entity.vo.customer.CustomerFundVo> list = customerFundService.queryList(customerFundvo);
        return getDataTable(list);
    }

    /**
     * 查询客户抵扣资金列表
     */
    @PreAuthorize(hasPermi = "CustomerFund:fund:list")
    @GetMapping("/list")
    public TableDataInfo list(CustomerFundDetail query) {
        if (query.getCreateTimeArr() != null && query.getCreateTimeArr().length>1){
            query.setStartDate(query.getCreateTimeArr()[0]);
            query.setEndDate(query.getCreateTimeArr()[1]);
        }
        if (StringUtils.isNotEmpty(query.getEndDate())){
            if (query.getEndDate().indexOf(":")<0){
                query.setEndDate(query.getEndDate()+" 23:59:59");
            }
        }
        return getDataTable(customerFundDetailService.queryDeductList(query));
    }

    /**
     * 扣除
     * @param customerFundvo
     * @return
     */
    @PostMapping("/deduct")
    public AjaxResult deduct(@RequestBody CustomerFundDetail customerFundvo) {


        if(customerFundvo.getAmount()==null || customerFundvo.getAmount()<0){
            return AjaxResult.error("抵扣数额必须大于0");
        }

        if (StringUtils.isEmpty(customerFundvo.getPhone())){
            return AjaxResult.error("客户信息不能为空");
        }
        /*
        if (customerFundvo.getPhone().length()!=11 || !customerFundvo.getPhone().startsWith("1") ){
            return AjaxResult.error("客户手机号码不正确");
        }*/
        /*
        CustomerInfo ci = customerInfoService.getCustomerByPhone(customerFundvo.getPhone());
        if (ci == null){
            return AjaxResult.error("没有找到手机号码对应的客户信息");
        }*/
        CustomerInfo ci = customerInfoService.getById(customerFundvo.getPhone());
        if (ci == null){
            return AjaxResult.error("没有找到客户信息");
        }
        CustomerFund fund = customerFundService.getByCustomerId(ci.getCustomerUid());
        if (fund == null){
            return AjaxResult.error("没有找到客户资金信息");
        }
        if (fund.getFreezeScore() == null){
            fund.setFreezeScore(0L);
        }
        if (fund.getFreezeRedBag() == null){
            fund.setFreezeRedBag(0L);
        }
        customerFundvo.setCustomerUid(ci.getCustomerUid());
        customerFundvo.setFundStatus("1");
        customerFundvo.setAmount(0-customerFundvo.getAmount());
        customerFundvo.setDataStatus(DataStatus.invalid.getKey());
        customerFundvo.setCreateName(SecurityUtils.getUsername());
        customerFundvo.setCreateUser(SecurityUtils.getUserId());
        customerFundvo.setCreateTime(new Date());
        customerFundvo.setBizTime(new Date());
        if (customerFundvo.getDeductType().equals("抵扣积分")){
            customerFundvo.setBizType("score");
        }else{
            customerFundvo.setBizType("paiban");
        }

        Long amount = Math.abs(customerFundvo.getAmount());
        if (customerFundvo.getBizType().equals("score")){
            if (fund.getScore()<(amount+fund.getFreezeScore())){
                return AjaxResult.error("该用户已冻结"+fund.getFreezeScore()+"积分,余额不足");
            }
            fund.setFreezeScore(fund.getFreezeScore()+amount);
        }else{
            if (fund.getRedBag()<(amount+fund.getFreezeRedBag())){
                return AjaxResult.error("该用户已冻结"+fund.getFreezeRedBag()+"次排版,余额不足");
            }
            fund.setFreezeRedBag(fund.getFreezeRedBag()+amount);
        }
        if (customerFundDetailService.save(customerFundvo)){
            customerFundService.updateById(fund);
        }
        return AjaxResult.success();
    }

    /**
     * 导出客户收益列表
     */
    @PreAuthorize(hasPermi = "CustomerFund:fund:export")
    @Log(title = "客户收益", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, com.probox.common.entity.vo.customer.CustomerFundVo customerFundvo) throws IOException {
        List<com.probox.common.entity.vo.customer.CustomerFundVo> list = customerFundService.queryList(customerFundvo);
        ExcelUtil<com.probox.common.entity.vo.customer.CustomerFundVo> util = new ExcelUtil<com.probox.common.entity.vo.customer.CustomerFundVo>(com.probox.common.entity.vo.customer.CustomerFundVo.class);
        util.exportExcel(response, list, "客户收益数据");
    }

    /**
     * 获取客户收益详细信息
     */
    @PreAuthorize(hasPermi = "CustomerFund:fund:query")
    @GetMapping(value = "/{fundUid}")
    public AjaxResult getInfo(@PathVariable("fundUid") Long fundUid) {
        return AjaxResult.success(customerFundService.selectCustomerFundById(fundUid));
    }

    /**
     * 新增客户收益
     */
    @PreAuthorize(hasPermi = "CustomerFund:fund:add")
    @Log(title = "客户收益", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CustomerFund customerFund) {
        return toAjax(customerFundService.insertCustomerFund(customerFund));
    }

    /**
     * 修改客户收益
     */
    @PreAuthorize(hasPermi = "CustomerFund:fund:edit")
    @Log(title = "客户收益", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CustomerFund customerFund) {
        return toAjax(customerFundService.updateCustomerFund(customerFund));
    }

    /**
     * 删除客户收益
     */
    @PreAuthorize(hasPermi = "CustomerFund:fund:remove")
    @Log(title = "客户收益", businessType = BusinessType.DELETE)
    @DeleteMapping("/{fundUid}")
    public AjaxResult remove(@PathVariable Long fundUid) {
        CustomerFundDetail cfd = customerFundDetailService.getById(fundUid);
        if (cfd == null){
            return toAjax(true);
        }
        if (cfd.getDataStatus().equals("0")){
            customerFundDetailService.removeById(cfd);
            CustomerFund fund =  customerFundService.getByCustomerId(cfd.getCustomerUid());
            if (fund != null){
                if (cfd.getBizType().equals("score")){
                    fund.setFreezeScore(fund.getFreezeScore()+cfd.getAmount());
                }else if (cfd.getBizType().equals("paiban")){
                    fund.setFreezeRedBag(fund.getFreezeRedBag()+cfd.getAmount());
                }
                customerFundService.updateById(fund);
            }
            return toAjax(true);
        }else{
            return AjaxResult.error("该数据不能删除");
        }
    }

    /**
     * 查看客户总收益
     */
    @PreAuthorize(hasPermi = "CustomerFund:fund:list")
    @GetMapping(value = "/getAllProfit")
    public TableDataInfo getAllProfit(CustomerFundDetail customerFundDetail) {
        startPage();
        List<CustomerFundDetail> customerFundDetails = customerFundDetailService.queryList(customerFundDetail);
        return getDataTable(customerFundDetails);
    }

    /**
     * 查看客户一级粉丝信息
     */
    @PreAuthorize(hasPermi = "CustomerFund:fund:list")
    @GetMapping(value = "/getFreeCustomerInfo/{customerUid}")
    public TableDataInfo getFreeCustomerInfo(@PathVariable Long customerUid) {
        String fansStatus = "1";
        startPage();
        List<CustomerInfo> customerInfoList = customerFundDetailService.getFreeCustomerInfo(customerUid,fansStatus);
        return getDataTable(customerInfoList);
    }

    /**
     * 查看客户二级粉丝信息
     */
    @PreAuthorize(hasPermi = "CustomerFund:fund:list")
    @GetMapping(value = "/getFreeSecondCustomerInfo/{customerUid}")
    public TableDataInfo getFreeSecondCustomerInfo(@PathVariable Long customerUid) {
        String fansStatus = "2";
        startPage();
        List<CustomerInfo> customerInfoList = customerFundDetailService.getFreeCustomerInfo(customerUid,fansStatus);
        return getDataTable(customerInfoList);
    }

}
